﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using BW.Mes.WinForms.BasicData;

namespace BW.Mes.WinForms.BasicData
{
    public partial class BomForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private readonly string _bomApiBaseUrl = "http://120.26.197.100:8022";

        public BomForm()
        {
            InitializeComponent();
            this.Load += BomForm_Load;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
            pagerControl1.PageChanged += PagerControl1_PageChanged;
        }

        private async void BomForm_Load(object sender, EventArgs e)
        {
            await LoadBomData(1, pagerControl1.PageSize);
        }

        private async Task LoadBomData(int pageIndex, int pageSize)
        {
            try
            {
                string url = $"T2/Bom/GetBom?PageIndex={pageIndex}&PageSize={pageSize}";
                var result = await GetApiDataAsync<BomListResponse>(url);
                gridControl1.DataSource = null;
                gridControl1.DataSource = result.pageDatas;
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();
                SetupGridActionColumn(); // 确保操作列在最后添加
                AfterBindBomData();
                pagerControl1.TotalCount = result.totalCount;
                pagerControl1.PageIndex = pageIndex;
                pagerControl1.PageSize = pageSize;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}", "错误");
            }
        }

        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            HttpResponseMessage response = await _httpClient.GetAsync($"{_bomApiBaseUrl}/{endpoint}");
            response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<T>(responseBody);
        }

        private void SetupGridActionColumn()
        {
            var actionColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            actionColumn.Caption = "操作";
            actionColumn.FieldName = "操作";
            actionColumn.Visible = true;
            actionColumn.VisibleIndex = gridView1.Columns.Count;

            var buttonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            buttonEdit.Buttons.Clear();

            var viewButton = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph);
            viewButton.Caption = "查看";
            viewButton.Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            viewButton.Appearance.ForeColor = System.Drawing.Color.Black;
            viewButton.Appearance.Options.UseForeColor = true;
            viewButton.Width = 60;
            buttonEdit.Buttons.Add(viewButton);
            buttonEdit.Buttons[0].Caption = "查看";
            buttonEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
            buttonEdit.Buttons[0].Appearance.ForeColor = System.Drawing.Color.Black;
            buttonEdit.Buttons[0].Appearance.Options.UseForeColor = true;

            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
            actionColumn.ColumnEdit = buttonEdit;

            gridView1.Columns.Add(actionColumn);
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
            if (gridView1.Columns.Count > 0)
                gridView1.Columns[0].VisibleIndex = 0;
        }

        private void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                var bom = gridView1.GetRow(rowHandle) as BomModel;
                if (bom != null)
                {
                    if (e.Button.Caption == "查看")
                    {
                        // 弹窗显示BOM详情，跳转到ALLBOM页面
                        var allBomForm = new ALLBOM(bom);
                        allBomForm.ShowDialog();
                    }
                }
            }
        }

        private async Task<bool> DeleteBomAsync(long bomId)
        {
            var response = await _httpClient.PutAsync($"{_bomApiBaseUrl}/T2/Bom/DeleteBom?id={bomId}", null);
            return response.IsSuccessStatusCode;
        }

        public class BomModel
        {
            public long Id { get; set; }
            [DisplayName("BOM编号")]
            public string BomCode { get; set; }
            [DisplayName("BOM名称")]
            public string BomName { get; set; }
            [DisplayName("版本号")]
            public string Version { get; set; }
            [DisplayName("类型")]
            public string BomType { get; set; }
            [DisplayName("日产量")]
            public string BomNumber { get; set; }
            [DisplayName("预计成本")]
            public string BomMoney { get; set; }
            [DisplayName("BOM描述")]
            public string BomMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }

        public class BomListResponse
        {
            public int totalCount { get; set; }
            public List<BomModel> pageDatas { get; set; }
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private async void btnAdd_Click(object sender, EventArgs e)
        {
            var addForm = new AddBomForm();
            if (addForm.ShowDialog() == DialogResult.OK)
            {
                await LoadBomData(1, pagerControl1.PageSize);
            }
        }
        private async void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var bom = gridView1.GetRow(selectedRows[0]) as BomModel;
            if (bom == null)
            {
                XtraMessageBox.Show("未获取到BOM信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var updateForm = new UpdateBomForm(bom);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                await LoadBomData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的BOM！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 个BOM吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            int successCount = 0;
            int failCount = 0;
            List<string> failedItems = new List<string>();

            foreach (var rowHandle in selectedRows)
            {
                var bom = gridView1.GetRow(rowHandle) as BomModel;
                if (bom != null)
                {
                    if (await DeleteBomAsync(bom.Id))
                    {
                        successCount++;
                    }
                    else
                    {
                        failCount++;
                        failedItems.Add(bom.BomName);
                    }
                }
            }

            string summaryMessage = $"删除操作完成。\n成功: {successCount}个\n失败: {failCount}个";
            if (failCount > 0)
            {
                summaryMessage += "\n失败的BOM：" + string.Join(", ", failedItems);
            }
            XtraMessageBox.Show(summaryMessage, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            if (successCount > 0)
            {
                await LoadBomData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }

        private async void btnRefresh_Click(object sender, EventArgs e)
        {
            await LoadBomData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindBomData()
        {
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
            // 斑马纹美化（车间管理同款粉色）
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#fde6f4");
            gridView1.Appearance.EvenRow.Options.UseBackColor = true;
            gridView1.Appearance.OddRow.BackColor = ColorTranslator.FromHtml("#fff6fb");
            gridView1.Appearance.OddRow.Options.UseBackColor = true;
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            // 表头同色
            gridView1.Appearance.HeaderPanel.BackColor = ColorTranslator.FromHtml("#fde6f4");
            gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
            // 选中行不覆盖背景色
            gridView1.Appearance.FocusedRow.BackColor = Color.Transparent;
            gridView1.Appearance.FocusedRow.Options.UseBackColor = false;
            gridView1.Appearance.HideSelectionRow.BackColor = Color.Transparent;
            gridView1.Appearance.HideSelectionRow.Options.UseBackColor = false;
            // 禁用皮肤影响
            gridView1.Appearance.Row.BackColor = Color.Empty;
            gridView1.Appearance.Row.Options.UseBackColor = false;
        }

        private async void PagerControl1_PageChanged(object sender, EventArgs e)
        {
            await LoadBomData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private long ExtractBomIdFromResponse(string responseBody)
        {
            // 假设返回格式为 { "id": 123, ... }
            var obj = JObject.Parse(responseBody);
            return obj["id"] != null ? (long)obj["id"] : 0;
        }
    }
}